import { signal, effect } from "@preact/signals"
import { createLogger } from "./logger"

const logger = createLogger("cached")

interface TokenState {
    accessToken: string
}

// 初始值
const INITIAL_TOKEN_STATE: TokenState = {
    accessToken: "",
}

// 從 sessionStorage 讀取初始值
function getInitialTokenState(): TokenState {
    try {
        const stored = sessionStorage.getItem("token")
        if (stored) {
            return JSON.parse(stored)
        }
    } catch (error) {
        logger.debug("Failed to parse stored token", error)
    }
    return INITIAL_TOKEN_STATE
}

// 創建 signal2025
const tokenSignal = signal<TokenState>(getInitialTokenState())

// 監聽變化並同步到 sessionStorage
effect(() => {
    try {
        sessionStorage.setItem("token", JSON.stringify(tokenSignal.value))
    } catch (error) {
        logger.debug("Failed to store token", error)
    }
})

// 導出的方法集合
export const CachedToken = {
    // 獲取當前 token 狀態
    get token() {
        return tokenSignal.value
    },

    // 設置 token 數據
    setTokenData(data: TokenState) {
        tokenSignal.value = {
            ...data,
        }
    },

    // 清除 token
    clearToken() {
        tokenSignal.value = INITIAL_TOKEN_STATE
    },

    // 獲取原始 signal（謹慎使用）
    _signals: {
        token: tokenSignal,
    },
}

// 為了保持與之前代碼的兼容性，提供一個快速訪問方法
export const getToken = () => tokenSignal.value

// 如果需要在非組件環境中使用
export const tokenStore = {
    get: () => tokenSignal.value,
    set: (value: TokenState) => {
        tokenSignal.value = value
    },
    clear: () => {
        tokenSignal.value = INITIAL_TOKEN_STATE
    },
    subscribe: (callback: (value: TokenState) => void) => {
        effect(() => {
            callback(tokenSignal.value)
        })
    },
}
